package com.ringtheweb.serviceprovider.weather.core;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ringtheweb.serviceprovider.weather.dao.ILocationDAO;
import com.ringtheweb.serviceprovider.weather.model.Location;


@Service("locationTreePersister")
public class LocationTreePersister {

	@Autowired
	ILocationDAO locationDAO;
	
	private static Log LOG = LogFactory.getLog(LocationTreePersister.class);
	
	
	public LocationTreePersister() {

	}
	
	public void beforeRetrieval(Location parentLocation) {
		// Reset list
		parentLocation.setChildren(new ArrayList<Location>());
		Location persistedLocation = locationDAO.findByNameAndParentWithChildren(parentLocation.getName(), 
				parentLocation.getParentLocation() == null ? null : 
					parentLocation.getParentLocation().getId());
		if (persistedLocation != null) {
			parentLocation.setId(persistedLocation.getId());
			parentLocation.setCompleted(persistedLocation.isCompleted());
			
			if (persistedLocation.getChildren()!=null) {
				parentLocation.addChildrenLocations(persistedLocation.getChildren());
			}
		}

		
	}
	
	// Work only of proxy-target-class is enabled since called internally
	@Transactional
	public void afterRetrieval(Location parentLocation) {
		LOG.debug(String.format("Persisting location %s)",parentLocation));
		long startTime = System.currentTimeMillis();
		
        if (parentLocation.getId() != null) {
    		
    		// Check if location has already been persisted
    		List<Location>	children = parentLocation.getChildren();
        	if (children != null && children.size() != 0 ) {
        		
        		if (children.get(0).getId() == null) {
            		Location persistedLocation = locationDAO.makePersistent(parentLocation);
            		// Set the persisted children (so that they have an id)
            		parentLocation.getChildren().clear();
            		parentLocation.addChildrenLocations(persistedLocation.getChildren());
        		}
        		else {
        			LOG.debug(String.format("Location %s already persisted", parentLocation));
        		}
        	}

        }
        else {
        	// it has already been loaded no need to check if it exists in database
        	locationDAO.saveOrUpdate(parentLocation);
        }
		
		long stopTime = System.currentTimeMillis();
		LOG.debug(String.format("Persisting execution time=%d",(stopTime-startTime)));
	}
	
	public void afterNextChild(Location parentLocation,Location childLocation) {
		childLocation.setCompleted(true);
		locationDAO.makePersistent(childLocation);
		childLocation = null;
	}
	
	@Transactional
	public void afterLastChild(Location parentLocation) {
        	parentLocation.setCompleted(true);
        	for (Location location : parentLocation.getChildren()) {
        		location.setCompleted(true);
        	}
        	locationDAO.makePersistent(parentLocation);
	}




}
